<template>
    <div>
        <a-dropdown placement="bottomRight" v-if="!hidden">
    <span class="ant-pro-account-avatar">
      <a-avatar
          :src="userInfo.headPortrait"
          class="antd-pro-global-header-index-avatar"
          size="small"/>
      <span>{{ userInfo.username }}</span>
    </span>
            <template v-slot:overlay>
                <a-menu :selected-keys="[]" class="ant-pro-drop-down menu">
                    <a-menu-item key="center" @click="handleToCenter">
                        <a-icon type="user"/>
                        修改密码
                    </a-menu-item>
                    <a-menu-item key="logout" @click="handleLogout">
                        <a-icon type="logout"/>
                        退出登录
                    </a-menu-item>
                </a-menu>
            </template>
        </a-dropdown>
        
        <a-modal
            :confirmLoading="modalLoading.loading1"
            :visible="modalShow.show1"
            :width="640"
            title="修改密码"
            @cancel="modalShow.show1 = false"
            @ok="handleConfirm()"
        >
            <a-form-model
                ref="ruleForm1"
                :model="modalForm.ruleForm1"
                :rules="modalRules.rules1"
                style="margin-bottom:20px"
                v-bind="formItemLayout">
                <a-form-model-item label="原密码" prop="oldpassword">
                    <a-input
                        v-model="modalForm.ruleForm1.oldpassword"></a-input>
                </a-form-model-item>
                <a-form-model-item label="新密码" prop="password">
                    <a-input v-model="modalForm.ruleForm1.password"></a-input>
                </a-form-model-item>
                <a-form-model-item label="确认新密码" prop="confirmpassword">
                    <a-input
                        v-model="modalForm.ruleForm1.confirmpassword"></a-input>
                </a-form-model-item>

                <div v-if="shows" style="color: red;line-height: 1.2;margin-left: 150px;">
                    为了确保您是具备权限的用户,<br>对超管进行相关操作时需要您再次输入超管密码
                </div>
                <a-form-model-item v-if="shows" label="超管密码" prop="captcha">
                    <a-input
                        v-model="modalForm.ruleForm1.captcha"></a-input>
                </a-form-model-item>
                
            </a-form-model>
        </a-modal>
    </div>
</template>

<script>
import {Modal} from 'ant-design-vue'
import {mapGetters} from 'vuex'
import {updateUserPassword} from "@/api/api";

const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/

export default {
    name: 'AvatarDropdown',
    computed: {
        ...mapGetters(['avatar', 'userInfo'])
    },
    props: {
        hidden: {
            type: Boolean,
            default: false
        },
        currentUser: {
            type: Object,
            default: () => null
        },
        menu: {
            type: Boolean,
            default: true
        }
    },
    data() {
        const that = this
        function validator(rule, value, callback) {
            if(!value) {
                callback(new Error('新密码不能为空！'))
            } else if (!reg.test(value)) {
                callback(new Error('密码必须8-16位且包含数字，大写字母，小写字母，特殊字符中的任意三种！'))
            } else {
                callback()
            }
        }
        function validatorConfirm(rule, value, callback) {
            if(!value) {
                callback(new Error('密码不能为空！'))
            } else if(that.modalForm.ruleForm1.password != value) {
                callback(new Error('密码不一致！！'))
            } else {
                callback()
            }
        }
        return {
            shows: false,
            formItemLayout: {
                labelCol: {
                    xs: {span: 24},
                    sm: {span: 6}
                },
                wrapperCol: {
                    xs: {span: 24},
                    sm: {span: 14}
                }
            },
            modalResetForm: {
                ruleForm1: {
                    oldpassword: '',
                    password: '',
                    confirmpassword: ''
                },
            },
            modalForm: {
                ruleForm1: {
                    oldpassword: '',
                    password: '',
                    confirmpassword: '',
                    captcha: ''
                },
            },
            modalRules: {
                rules1: {
                    oldpassword: [{required: true, message: '旧密码不能为空'}],
                    password: [{required: true, validator}],
                    confirmpassword: [{required: true, validator: validatorConfirm}],
                    captcha: [{required: true, message: '请输入管理员密码'}],
                },
            },
            modalLoading: {
                loading1: false
            },
            modalShow: {
                show1: false
            }
        }
    },
    mounted() {
        console.log(this.userInfo)
        if(this.userInfo.username === 'admin') this.shows = true
    },
    methods: {
        handleToCenter() {
            this.modalShow.show1 = true
        },
        handleToSettings() {
            this.$router.push({path: '/account/settings'})
        },
        handleLogout(e) {
            console.log(sessionStorage.getItem('paths'))
            Modal.confirm({
                title: this.$t('layouts.usermenu.dialog.title'),
                content: this.$t('layouts.usermenu.dialog.content'),
                onOk: () => {
                    return this.$store.dispatch('Logout').then(() => {
                        this.$router.replace({path: sessionStorage.getItem('paths') || '/auth/login' })
                    })
                },
                onCancel() {
                }
            })
        },
        handleConfirm(param = {}) {
            const h = this.$createElement;
            const that = this
            this.$refs.ruleForm1.validate((valid) => {
                if (valid) {
                    if (this.modalForm.ruleForm1.password !== this.modalForm.ruleForm1.confirmpassword) {
                        this.$message.error('两次密码输入不一致')
                    } else {
                        console.log(this.userInfo)
                        updateUserPassword({
                            username: this.userInfo.username,
                            password: this.modalForm.ruleForm1.password,
                            oldPassword: this.modalForm.ruleForm1.oldpassword,
                            id: this.userInfo.uid,
                            captcha: this.modalForm.ruleForm1.captcha,
                            ...param
                        }).then(res => {
                            this.$message.success(res.msg)
                            this.modalForm.ruleForm1.password = ''
                            this.modalForm.ruleForm1.confirmpassword = ''
                            this.modalForm.ruleForm1.oldpassword = ''
                            this.$nextTick(() => {
                                this.$refs['ruleForm1'].clearValidate()
                            })
                            this.modalShow.show1 = false
                        }).catch((err) => {
                            if(err.code == 999999) {
                                this.modalShow.show1 = false
                                let pwd = ''
                                this.$info({
                                    title: '请输入管理员密码！',
                                    content: h('div', {}, [
                                        h('a-input', {
                                            on: {
                                                input(e) {
                                                    pwd = e.target.value
                                                }
                                            }
                                        }),
                                    ]),
                                    onOk() {
                                        that.handleConfirm({captcha: pwd})
                                    },
                                });
                            }
                            this.modalLoading.loading2 = false
                        })
                    }
                }
            })
        }
    }
}
</script>

<style lang="less" scoped>
.ant-pro-drop-down {
    /deep/ .action {
        margin-right: 8px;
    }
    
    /deep/ .ant-dropdown-menu-item {
        min-width: 160px;
    }
}
.antd-pro-global-header-index-avatar {
    background: #ddd !important;
}
</style>
